<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <title>渐进式开发 - 为企业级框架和应用而生</title>
  <meta charset="utf-8">
  <meta name="description" content="index.description">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <link rel="icon" href="/images/favicon.png" type="image/x-icon">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.css" />
<link rel="stylesheet" href="/css/index.css">

    <script>
    !function(t,e,a,r,c){t.TracertCmdCache=t.TracertCmdCache||[],t[c]=window[c]||
      {_isInit:!0,call:function(){t.TracertCmdCache.push(arguments)},
      start:function(t){this.call('start',t)}},t[c].l=new Date;
      var n=e.createElement(a),s=e.getElementsByTagName(a)[0];
      n.async=!0,n.src=r,s.parentNode.insertBefore(n,s)}
    (window,document,'script','https://tracert.alipay.com/tracert.js','Tracert');
      Tracert.start({
        plugins: [ 'BucName' ],
        spmAPos: 'a454',
        spmBPos: 'b4893',
      });
    </script>
  
</head>
<body>
  <div class="nav" >
  <header>
    <a href="/zh-cn/" class="nav-logo leftpadding" alt="egg"><img src="https://zos.alipayobjects.com/rmsportal/VTcUYAaoKqXyHJbLAPyF.svg"></a>
    <ul class="nav-item">
      <li>
        <form id="search-form">
          <input type="text" id="search-query" class="search-query st-default-search-input">
        </form>
      </li>
      <li><a href="/zh-cn/intro/" alt="指南">指南</a></li><li><a href="/api/" alt="API">API</a></li><li><a href="/zh-cn/tutorials/index.html" alt="教程">教程</a></li><li><a href="https://github.com/search?q=topic%3Aegg-plugin&type=Repositories" alt="插件">插件</a></li><li><a href="https://github.com/eggjs/egg/releases" alt="发布日志">发布日志</a></li>
      
      
        <li class="translations">
          <a class="nav-link">Translations</a>
          <span class="arrow"></span><ul id="dropdownContent" class="dropdown-content"><li><a id="en" href="/en/tutorials/progressive.html" >English</a></li><li><a id="zh-cn" href="/zh-cn/tutorials/progressive.html" style="color: #22ab28">中文</a></li></ul>
        </li>
      
      <li><iframe src="https://ghbtns.com/github-btn.html?user=eggjs&repo=egg&type=star&count=true" frameborder="0" scrolling="0" width="150px" height="20px"></iframe></li>
    </ul>
    <a id="mobileTrigger" href="#" class="mobile-trigger">
      <ul>
        <li></li>
        <li></li>
        <li></li>
      </ul>
    </a>
  </header>
</div>
  <div id="container" class="container">
    <div class="page-main">
  <article class="markdown-body">
    <h1>渐进式开发</h1>
    <p>在 Egg 里面，有<a href="../basics/plugin.html">插件</a>，也有<a href="../advanced/framework.html">框架</a>，前者还包括了 <code>path</code> 和 <code>package</code> 两种加载模式，那我们应该如何选择呢？</p>
<p>本文将以实例的方式，一步步给大家演示下，如何渐进式地进行代码演进。</p>
<p>全部的示例代码可以参见 <a href="https://github.com/eggjs/examples/tree/master/progressive" target="_blank" rel="noopener">eggjs/examples/progressive</a>。</p>
<h2 id="最初始的状态"><a class="markdown-anchor" href="#最初始的状态">#</a> 最初始的状态</h2>
<p>假设我们有一段分析 UA 的代码，实现以下功能：</p>
<ul>
<li><code>ctx.isAndroid</code></li>
<li><code>ctx.isIOS</code></li>
</ul>
<p>通过之前的教程，大家一定可以很快的写出来，我们快速回顾下：</p>
<p>对应的代码参见 <a href="https://github.com/eggjs/examples/tree/master/progressive/step1" target="_blank" rel="noopener">step1</a>。</p>
<p>目录结构：</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">example-app</span><br><span class="line">├── app</span><br><span class="line">│   ├── extend</span><br><span class="line">│   │   └── context.js</span><br><span class="line">│   └── router.js</span><br><span class="line">├── <span class="built_in">test</span></span><br><span class="line">│   └── index.test.js</span><br><span class="line">└── package.json</span><br></pre></td></tr></table></figure>
<p>核心代码：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// app/extend/context.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  get isIOS() &#123;</span><br><span class="line">    <span class="keyword">const</span> iosReg = <span class="regexp">/iphone|ipad|ipod/i</span>;</span><br><span class="line">    <span class="keyword">return</span> iosReg.test(<span class="keyword">this</span>.get(<span class="string">'user-agent'</span>));</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="插件的雏形"><a class="markdown-anchor" href="#插件的雏形">#</a> 插件的雏形</h2>
<p>我们很明显能感知到，这段逻辑是具备通用性的，可以写成插件。</p>
<p>但一开始的时候，功能还没完善，直接独立插件，维护起来比较麻烦。</p>
<p>此时，我们可以把代码写成插件的形式，但并不独立出去。</p>
<p>对应的代码参见 <a href="https://github.com/eggjs/examples/tree/master/progressive/step2" target="_blank" rel="noopener">step2</a>。</p>
<p>新的目录结构：</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">example-app</span><br><span class="line">├── app</span><br><span class="line">│   └── router.js</span><br><span class="line">├── config</span><br><span class="line">│   └── plugin.js</span><br><span class="line">├── lib</span><br><span class="line">│   └── plugin</span><br><span class="line">│       └── egg-ua</span><br><span class="line">│           ├── app</span><br><span class="line">│           │   └── extend</span><br><span class="line">│           │       └── context.js</span><br><span class="line">│           └── package.json</span><br><span class="line">├── <span class="built_in">test</span></span><br><span class="line">│   └── index.test.js</span><br><span class="line">└── package.json</span><br></pre></td></tr></table></figure>
<p>核心代码：</p>
<ul>
<li>
<p><code>app/extend/context.js</code> 移动到 <code>lib/plugin/egg-ua/app/extend/context.js</code>。</p>
</li>
<li>
<p><code>lib/plugin/egg-ua/package.json</code> 声明插件。</p>
</li>
</ul>
<figure class="highlight json"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"eggPlugin"</span>: &#123;</span><br><span class="line">    <span class="attr">"name"</span>: <span class="string">"ua"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>config/plugin.js</code> 中通过 <code>path</code> 来挂载插件。</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// config/plugin.js</span></span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>);</span><br><span class="line">exports.ua = &#123;</span><br><span class="line">  enable: <span class="literal">true</span>,</span><br><span class="line">  path: path.join(__dirname, <span class="string">'../lib/plugin/egg-ua'</span>),</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="抽成独立插件"><a class="markdown-anchor" href="#抽成独立插件">#</a> 抽成独立插件</h2>
<p>经过一段时间开发后，该模块的功能成熟，此时可以考虑抽出来成为独立的插件。</p>
<p>首先，我们抽出一个 egg-ua 插件，看过<a href="../advanced/plugin.html">插件文档</a>的同学应该都比较熟悉，我们这里只简单过一下：</p>
<p>目录结构：</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">egg-ua</span><br><span class="line">├── app</span><br><span class="line">│   └── extend</span><br><span class="line">│       └── context.js</span><br><span class="line">├── <span class="built_in">test</span></span><br><span class="line">│   ├── fixtures</span><br><span class="line">│   │   └── <span class="built_in">test</span>-app</span><br><span class="line">│   │       ├── app</span><br><span class="line">│   │       │   └── router.js</span><br><span class="line">│   │       └── package.json</span><br><span class="line">│   └── ua.test.js</span><br><span class="line">└── package.json</span><br></pre></td></tr></table></figure>
<p>对应的代码参见 <a href="https://github.com/eggjs/examples/tree/master/progressive/step3/egg-ua" target="_blank" rel="noopener">step3/egg-ua</a>。</p>
<p>然后改造原有的应用，对应的代码参见 <a href="https://github.com/eggjs/examples/tree/master/progressive/step3/example-app" target="_blank" rel="noopener">step3/example-app</a>。</p>
<ul>
<li>移除 <code>lib/plugin/egg-ua</code> 目录。</li>
<li><code>package.json</code> 中声明对 <code>egg-ua</code> 的依赖。</li>
<li><code>config/plugin.js</code> 中修改依赖声明为 <code>package</code> 方式。</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// config/plugin.js</span></span><br><span class="line">exports.ua = &#123;</span><br><span class="line">  enable: <span class="literal">true</span>,</span><br><span class="line">  package: <span class="string">'egg-ua'</span>,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p><strong>注意：在插件还没发布前，可以通过 <code>npm link</code> 的方式进行本地测试，具体参见 <a href="https://docs.npmjs.com/cli/link" target="_blank" rel="noopener">npm-link</a>。</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">$ <span class="built_in">cd</span> example-app</span><br><span class="line">$ npm link ../egg-ua</span><br><span class="line">$ npm i</span><br><span class="line">$ npm <span class="built_in">test</span></span><br></pre></td></tr></table></figure>
<h2 id="沉淀到框架"><a class="markdown-anchor" href="#沉淀到框架">#</a> 沉淀到框架</h2>
<p>重复上述的过程，很快我们会积累了好几个插件和配置，并且我们会发现，在团队的大部分项目中，都会用到这些插件。</p>
<p>此时，就可以考虑抽象出一个适合团队业务场景的框架。</p>
<p>首先，抽象出 example-framework 框架，如上看过<a href="../advanced/framework.html">框架文档</a>的同学应该都比较熟悉，我们这里只简单过一下：</p>
<p>目录结构：</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">example-framework</span><br><span class="line">├── config</span><br><span class="line">│   ├── config.default.js</span><br><span class="line">│   └── plugin.js</span><br><span class="line">├── lib</span><br><span class="line">│   ├── agent.js</span><br><span class="line">│   └── application.js</span><br><span class="line">├── <span class="built_in">test</span></span><br><span class="line">│   ├── fixtures</span><br><span class="line">│   │   └── <span class="built_in">test</span>-app</span><br><span class="line">│   └── framework.test.js</span><br><span class="line">├── README.md</span><br><span class="line">├── index.js</span><br><span class="line">└── package.json</span><br></pre></td></tr></table></figure>
<ul>
<li>对应的代码参见 <a href="https://github.com/eggjs/examples/tree/master/progressive/step4/example-framework" target="_blank" rel="noopener">example-framework</a>。</li>
<li>把原来的 <code>egg-ua</code> 等插件的依赖，从 example-app 中移除，配置到该框架的 <code>package.json</code> 和 <code>config/plugin.js</code> 中。</li>
</ul>
<p>然后改造原有的应用，对应的代码参见 <a href="https://github.com/eggjs/examples/tree/master/progressive/step4/example-app" target="_blank" rel="noopener">step4/example-app</a>。</p>
<ul>
<li>移除 <code>config/plugin.js</code> 中对 <code>egg-ua</code> 的依赖。</li>
<li><code>package.json</code> 中移除对 <code>egg-ua</code> 的依赖。</li>
<li><code>package.json</code> 中声明对 <code>example-framework</code> 的依赖，并配置 <code>egg.framework</code>。</li>
</ul>
<figure class="highlight json"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"name"</span>: <span class="string">"progressive"</span>,</span><br><span class="line">  <span class="attr">"version"</span>: <span class="string">"1.0.0"</span>,</span><br><span class="line">  <span class="attr">"private"</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="attr">"egg"</span>: &#123;</span><br><span class="line">    <span class="attr">"framework"</span>: <span class="string">"example-framework"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">"dependencies"</span>: &#123;</span><br><span class="line">    <span class="attr">"example-framework"</span>: <span class="string">"*"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>注意：在框架还没发布前，可以通过 <code>npm link</code> 的方式进行本地测试，具体参见 <a href="https://docs.npmjs.com/cli/link" target="_blank" rel="noopener">npm-link</a>。</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">$ <span class="built_in">cd</span> example-app</span><br><span class="line">$ npm link ../egg-framework</span><br><span class="line">$ npm i</span><br><span class="line">$ npm <span class="built_in">test</span></span><br></pre></td></tr></table></figure>
<h2 id="写在最后"><a class="markdown-anchor" href="#写在最后">#</a> 写在最后</h2>
<p>综上所述，大家可以看到，我们是如何一步步渐进的去进行框架演进，得益于 Egg 强大的插件机制，代码的共建，复用和下沉，竟然可以这么的无痛。</p>
<ul>
<li>一般来说，当应用中有可能会复用到的代码时，直接放到 <code>lib/plugin</code> 目录去，如例子中的 <code>egg-ua</code>。</li>
<li>当该插件功能稳定后，即可独立出来作为一个 <code>node module</code> 。</li>
<li>如此以往，应用中相对复用性较强的代码都会逐渐独立为单独的插件。</li>
<li>当你的应用逐渐进化到针对某类业务场景的解决方案时，将其抽象为独立的 framework 进行发布。</li>
<li>当在新项目中抽象出的插件，下沉集成到框架后，其他项目只需要简单的重新 <code>npm install</code> 下就可以使用上，对整个团队的效率有极大的提升。</li>
<li><strong>注意：不管是应用/插件/框架，都必须编写单元测试，并尽量实现 100% 覆盖率。</strong></li>
</ul>

  </article>
  <aside id="mobileAside" class="toc">
  <div class="mobile-menu">
    <ul>
      <li><a href="/zh-cn/intro/" alt="指南">指南</a></li><li><a href="/api/" alt="API">API</a></li><li><a href="/zh-cn/tutorials/index.html" alt="教程">教程</a></li><li><a href="https://github.com/search?q=topic%3Aegg-plugin&type=Repositories" alt="插件">插件</a></li><li><a href="https://github.com/eggjs/egg/releases" alt="发布日志">发布日志</a></li>
      
      
        <li class="translations">
          <a class="nav-link">Translations</a>
          <span class="arrow"></span><ul id="dropdownContent" class="dropdown-content"><li><a id="en" href="/en/tutorials/progressive.html" >English</a></li><li><a id="zh-cn" href="/zh-cn/tutorials/progressive.html" style="color: #22ab28">中文</a></li></ul>
        </li>
      
    </ul>
  </div>
  <dl><dt id="title-Intro" style="cursor: pointer;" class="aside-title">新手指南<a id="collapse-icon-Intro" class="icon opend"></a></dt><dd id=panel-Intro><ul><li><a href="/zh-cn/intro/index.html" class="menu-link">Egg.js 是什么?</a></li><li><a href="/zh-cn/intro/egg-and-koa.html" class="menu-link">Egg.js 和 Koa</a></li><li><a href="/zh-cn/intro/quickstart.html" class="menu-link">快速入门</a></li><li><a href="/zh-cn/tutorials/progressive.html" class="menu-link">渐进式开发</a></li><li><a href="/zh-cn/migration.html" class="menu-link">2.x 升级指南</a></li></ul></dd><dt id="title-Basics" style="cursor: pointer;" class="aside-title">基础功能<a id="collapse-icon-Basics" class="icon opend"></a></dt><dd id=panel-Basics><ul><li><a href="/zh-cn/basics/structure.html" class="menu-link">目录结构</a></li><li><a href="/zh-cn/basics/objects.html" class="menu-link">内置对象</a></li><li><a href="/zh-cn/basics/env.html" class="menu-link">运行环境</a></li><li><a href="/zh-cn/basics/config.html" class="menu-link">配置</a></li><li><a href="/zh-cn/basics/middleware.html" class="menu-link">中间件</a></li><li><a href="/zh-cn/basics/router.html" class="menu-link">Router</a></li><li><a href="/zh-cn/basics/controller.html" class="menu-link">Controller</a></li><li><a href="/zh-cn/basics/service.html" class="menu-link">Service</a></li><li><a href="/zh-cn/basics/plugin.html" class="menu-link">插件</a></li><li><a href="/zh-cn/basics/schedule.html" class="menu-link">定时任务</a></li><li><a href="/zh-cn/basics/extend.html" class="menu-link">框架扩展</a></li><li><a href="/zh-cn/basics/app-start.html" class="menu-link">启动自定义</a></li></ul></dd><dt id="title-Core" style="cursor: pointer;" class="aside-title">核心功能<a id="collapse-icon-Core" class="icon opend"></a></dt><dd id=panel-Core><ul><li><a href="/zh-cn/core/development.html" class="menu-link">本地开发</a></li><li><a href="/zh-cn/core/unittest.html" class="menu-link">单元测试</a></li><li><a href="/zh-cn/core/deployment.html" class="menu-link">应用部署</a></li><li><a href="/zh-cn/core/logger.html" class="menu-link">日志</a></li><li><a href="/zh-cn/core/httpclient.html" class="menu-link">HttpClient</a></li><li><a href="/zh-cn/core/cookie-and-session.html" class="menu-link">Cookie and Session</a></li><li><a href="/zh-cn/core/cluster-and-ipc.html" class="menu-link">多进程模型和进程间通讯</a></li><li><a href="/zh-cn/core/view.html" class="menu-link">模板渲染</a></li><li><a href="/zh-cn/core/error-handling.html" class="menu-link">异常处理</a></li><li><a href="/zh-cn/core/security.html" class="menu-link">安全</a></li><li><a href="/zh-cn/core/i18n.html" class="menu-link">国际化</a></li></ul></dd><dt id="title-Tutorials" style="cursor: pointer;" class="aside-title">教程<a id="collapse-icon-Tutorials" class="icon opend"></a></dt><dd id=panel-Tutorials><ul><li><a href="/zh-cn/tutorials/mysql.html" class="menu-link">MySQL</a></li><li><a href="/zh-cn/tutorials/restful.html" class="menu-link">RESTful API</a></li><li><a href="/zh-cn/tutorials/passport.html" class="menu-link">Passport 鉴权</a></li><li><a href="/zh-cn/tutorials/socketio.html" class="menu-link">Socket.IO</a></li><li><a href="/zh-cn/tutorials/assets.html" class="menu-link">静态资源</a></li><li><a href="/zh-cn/tutorials/typescript.html" class="menu-link">TypeScript</a></li></ul></dd><dt id="title-Advanced" style="cursor: pointer;" class="aside-title">进阶<a id="collapse-icon-Advanced" class="icon opend"></a></dt><dd id=panel-Advanced><ul><li><a href="/zh-cn/advanced/loader.html" class="menu-link">Loader</a></li><li><a href="/zh-cn/advanced/plugin.html" class="menu-link">插件开发</a></li><li><a href="/zh-cn/advanced/framework.html" class="menu-link">框架开发</a></li><li><a href="/zh-cn/advanced/cluster-client.html" class="menu-link">多进程研发模式增强</a></li><li><a href="/zh-cn/advanced/view-plugin.html" class="menu-link">模板插件开发规范</a></li><li><a href="/zh-cn/style-guide.html" class="menu-link">代码风格指南</a></li></ul></dd><dt id="title-Community" style="cursor: pointer;" class="aside-title">社区<a id="collapse-icon-Community" class="icon opend"></a></dt><dd id=panel-Community><ul><li><a href="/zh-cn/plugins/" class="menu-link">内置插件列表</a></li><li><a href="/zh-cn/contributing.html" class="menu-link">如何贡献</a></li><li><a href="/zh-cn/resource.html" class="menu-link">资源</a></li><li><a href="/zh-cn/faq.html" class="menu-link">常见问题</a></li></ul></dd></dl>
</aside>
<script>
var mobileTrigger = document.getElementById('mobileTrigger');
var mobileAside = document.getElementById('mobileAside');

var expandMenu = function(title) {
  // handle icon
  const collapseIcon = document.getElementById('collapse-icon-' + title);
  if (collapseIcon) {
    collapseIcon.className = 'icon opend';
  }
  // handle panelEle
  const panelEle = document.getElementById('panel-' + title);
  if (panelEle) {
    panelEle.className = '';
  }
}

var collapseMenu = function(title) {
  // handle icon
  const collapseIcon = document.getElementById('collapse-icon-' + title);
  if (collapseIcon) {
    collapseIcon.className = 'icon closed';
  }
  // handle panelEle
  const panelEle = document.getElementById('panel-' + title);
  if (panelEle) {
    panelEle.className = 'aside-panel-hidden';
  }
}

mobileAside.onclick = function(e) {
  const targetId = e.target.id;
  if (targetId && (targetId.indexOf('title-') > -1 || targetId.indexOf('collapse-icon-') > -1)) {
    const title = targetId.replace('title-', '').replace('collapse-icon-', '');
    try { 
      // the the browser may have no localStroage or JSON.parse may throw exception.
      const menuInfo = JSON.parse(window.localStorage.getItem('menuInfo'));
        
      // current menu status
      const curClosed = menuInfo[title] ? menuInfo[title].closed : false; // default false

      // change UI
      curClosed ? expandMenu(title) : collapseMenu(title);

      // save menuInfo to localStorage
      menuInfo[title] = { closed: !curClosed } // opposite
      window.localStorage.setItem('menuInfo', JSON.stringify(menuInfo));
    } catch (e) {}
  }
};

mobileTrigger.onclick = function(e) {
  e.preventDefault();
  if (mobileAside.className.indexOf('mobile-show') === -1) {
    mobileAside.className += ' mobile-show';
  } else {
    mobileAside.className = 'toc';
  }
};

(function() {
  // save data to localStorage because the page will refresh when user change the url.
  let menuInfo;
  try { 
    // the the browser may have no localStroage or JSON.parse may throw exception.
    menuInfo = JSON.parse(window.localStorage.getItem('menuInfo'));
    if (!menuInfo) {
      menuInfo = {};
      window.localStorage.setItem('menuInfo', JSON.stringify(menuInfo));
    }
  } catch (e) {
    menuInfo = {}; // default {}
  }

  for (const title in menuInfo) {
    if (menuInfo[title] && menuInfo[title].closed) { // menu in closed status.
      collapseMenu(title);
    } else {
      expandMenu(title);
    }
  }

  // highlight menu
  const pathname = window.location.pathname;
  const selector = `a[href="${pathname}"].menu-link,a[href="${pathname}index.html"].menu-link`;
  const menuItem = mobileAside.querySelector(selector);
  if (menuItem) { menuItem.className += ' highlight'; }
})();
</script>

</div>

  </div>
</body>
<script src="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.js"></script>
<script>
docsearch({
  apiKey: '1561de31a86f79507ea00cdb54ce647c',
  indexName: 'eggjs',
  inputSelector: '#search-query',
});
</script>
<div class="cnzz">
<script src="https://s11.cnzz.com/z_stat.php?id=1261142226&web_id=1261142226" language="JavaScript"></script>
</div>

</html>
